package middlewares

import (
	"github.com/gin-gonic/gin"
	"hr/controllers"
	jwt2 "hr/pkg/jwt"
	"net/http"
	"strings"
)

func JwtAuthMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		authHeader := c.Request.Header.Get("Authorization")
		if authHeader == "" {
			controllers.ResponseError(c, controllers.CodeInvalidParam)
			c.Abort()
			return
		}
		parts := strings.SplitN(authHeader, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(http.StatusOK, gin.H{
				"code": 2323,
				"msg":  "格式有望",
			})
			c.Abort()
			return
		}
		token, err := jwt2.ParseToken(authHeader)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 2323,
				"msg":  "无效token",
			})
			c.Abort()
			return
		}
		//设置上下文
		c.Set(controllers.UserIdKey, token.UserId)
		c.Next()
	}
}
